<script setup lang="ts">
import {
  copyProduct,
  deleteProduct,
  getProductList,
  getProductOptions,
  ProductForm,
  ProductPageVO,
  ProductQuery
} from "@/api/product";
import {goodsStatusOpts} from "@/utils/status";
import defaultSettings from "@/settings";

defineOptions({
  name: "ProductIndex",
  inheritAttrs: false,
});

const queryFormRef = ref(ElForm);
const dataFormRef = ref(ElForm);

const loading = ref(false);
const ids = ref<number[]>([]);

const lists = ref<ProductPageVO[]>();
const total = ref(0); // 数据总数
const shopList = ref<any[]>([])
const current_role = localStorage.getItem("role_name");

const detailVisible = ref(false);
const editVisible = ref(false);

const currentId = ref<number | undefined>();
const statusOpts = goodsStatusOpts();

const queryParams = reactive<ProductQuery>({
  pageNum: 1,
  pageSize: 10,
  product_type: 1,
});

const dialog = reactive({
  title: "",
  visible: false,
});

const formData = reactive<ProductForm>({
  status: 1,
});

const rules = reactive({});

/** 查询 */
function handleQuery() {
  loading.value = true;
  getProductList(queryParams)
    .then(({data}) => {
      lists.value = data.items || [];
      total.value = data.total;
    }).catch(errmsg => {
    console.log("errmsg: " + errmsg)
  }).finally(() => {
    loading.value = false;
  });
}

/**
 * 重置查询
 */
function resetQuery() {
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;
  handleQuery();
}

/**  重置字典类型表单 */
function resetForm() {
  dataFormRef.value.resetFields();
  dataFormRef.value.clearValidate();

  formData.id = undefined;
  formData.status = 1;
}

/** 删除字典类型 */
function handleDelete(id?: number) {
  const productIds = [id || ids.value].join(",");
  if (!productIds) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "温馨提示", {
    cancelButtonText: "取消",
    confirmButtonText: "确定",
    type: "warning",
  }).then(() => {

    loading.value = true;
    deleteProduct(productIds).then(() => {
      ElMessage.success("删除成功");
      handleQuery();
    }).finally(() => {
      loading.value = false;
    });

  }).catch(errmsg => {

  });
}

/**
 * 编辑
 * @param id
 */
async function openDialog(type: number, id?: number) {

  if (!type) {
    ElMessage.warning("请勾选删除项");
  }

  if (id)
    currentId.value = id;

  if (type == 2) { // 详情
    detailVisible.value = true;
  } else {//编辑
    editVisible.value = true;
  }

}

async function closeDialog(type?: any) {
  editVisible.value = false;
  currentId.value = undefined;
  loading.value = false;

  if (type == 1) {
    handleQuery();
  }
}

function updateVisble() {
  editVisible.value = false;
}

onMounted(() => {
  handleQuery();
  initProductData();
});

/**
 * 初始化数据
 */
function initProductData() {
  getProductOptions().then(({data}) => {
    loading.value = false;
    shopList.value = data.shops || [];

    if (current_role != 'sys') {
      queryParams.shop_id = shopList.value[0].id;
    }

  }).finally(() => {
    loading.value = false;
  });
}


/**
 * 复制记录
 * @param id
 */
function copyRow(id: number) {
  if (!id) {
    ElMessage.warning("数据错误");
    return;
  }
  ElMessageBox.confirm("确认复制套餐?", "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    loading.value = true;
    copyProduct(id)
      .then((data) => {
        ElMessage.success("复制成功");
        resetQuery();
      })
      .finally(() => (loading.value = false));
  });
}

const tagTypes = ref<any[]>([
  "primary", "success", "info", "warning", "danger"
])
</script>

<template>
  <div class="app-container">
    <div class="search-container">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true" class="pull-left">
        <el-form-item label="" prop="shop_id" style="width: 160px;" v-if="current_role == 'sys'">
          <el-select v-model="queryParams.shop_id" placeholder="请选择店铺">
            <el-option :label="op.title" v-for="op in shopList" :value="Number(op.id)"/>
          </el-select>
        </el-form-item>
        <el-form-item label="" prop="category_id" style="width: 160px;">
          <el-select v-model="queryParams.category_id" clearable placeholder="请选择分类">
            <template v-for="op in shopList">
              <el-option :label="cop.title" v-for="cop in op.categories" :value="Number(cop.id)"
                         v-if="queryParams.shop_id == op.id"/>
            </template>
          </el-select>
        </el-form-item>
        <el-form-item label="" prop="keywords">
          <el-input
            v-model="queryParams.keywords"
            placeholder="套餐名称"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery()"
          >
            <i-ep-search/>
            搜索
          </el-button>
          <el-button @click="resetQuery()">
            <i-ep-refresh/>
            重置
          </el-button>
        </el-form-item>
      </el-form>

      <!--      v-hasPerm="['product:add']"-->
      <el-button type="success" @click="openDialog(1)" class="pull-right">
        <i-ep-plus/>
        新增
      </el-button>
      <div class="clear"></div>
    </div>

    <el-card class="table-container">
      <el-table
        v-loading="loading"
        highlight-current-row
        :data="lists"
      >
        <el-table-column label="编号" prop="sn"/>
        <el-table-column label="商品" prop="name" width="200">
          <template #default="scope">
            <el-row style="width: 200px;">
              <el-col :span="7">
                <el-avatar shape="square" :size="50" :src="defaultSettings.imgDomain + scope.row.thumb"
                           v-if="scope.row.thumb"/>
              </el-col>
              <el-col :span="17" style="margin: 0px;">
                <div class="c0"><strong>{{ scope.row.title }}</strong></div>
                <!--                <div v-if="scope.row.sn">编号：{{ scope.row.sn }}</div>-->
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column label="分类" prop="category_title"/>
        <el-table-column label="价格" prop="price"/>
        <el-table-column label="打包费" prop="bag_price"/>
        <el-table-column label="库存" prop="stock"/>
        <el-table-column label="商品" prop="products" width="180">
          <template #default="scope">
            <template v-for="(product, pidx) in scope.row.products" v-if="scope.row.product_type == 1">
              <div class="margin3-b"><strong>{{ product.title }}</strong> <span> x{{ product.amount }}</span></div>
              <el-tag :type="tagTypes[pidx%3] || 'info'" v-for="(tag,tidx) in product['spec_items']"
                      style="margin-bottom: 5px;">{{ tag.sn }}-{{ tag.title }} x{{ tag.amount }}
              </el-tag>
            </template>
          </template>
        </el-table-column>

        <!--        <el-table-column label="月售" prop="price"/>-->
        <el-table-column label="所属店铺" prop="shop_title"/>
        <el-table-column label="套餐状态" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.status == 1 ? 'success' :'danger'">{{ statusOpts[scope.row.status] }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="更新时间" prop="update_time"/>
        <el-table-column fixed="right" label="操作" align="left" width="130">
          <template #default="scope">
            <el-button v-hasPerm="['product:combo:copy']" type="primary" size="small" link
                       @click="copyRow(scope.row.id)">
              <i-ep-DocumentCopy class="margin3-r"/>
              复制
            </el-button>
            <el-button type="primary" link size="small" @click.stop="openDialog(1,scope.row.id)">
              <i-ep-edit/>
              编辑
            </el-button>
            <el-button type="danger" link size="small" @click.stop="handleDelete(scope.row.id)">
              <i-ep-delete/>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="handleQuery"
      />
    </el-card>

    <!--    编辑-->
    <EditCombo
      :visible="editVisible"
      :productId="currentId"
      @close="closeDialog"
      @updateVisble="updateVisble"
    />

  </div>
</template>
<style>
.el-table__cell .el-button {
  margin-bottom: 5px;
}

.el-table__cell .el-button + .el-button {
  margin-left: 0px;
}
</style>
